//
//  QRLocationParser.m
//  QRCodeManager
//
//  Created by Cosmin Stirbu on 4/17/13.
//  Copyright (c) 2013 Cosmin Stirbu. All rights reserved.
//

#import "QRLocationParser.h"
#import "CoreDataManager.h"

@implementation QRLocationParser

- (QRLocation *)qrLocation {
    NSManagedObjectContext *context = [CoreDataManager sharedInstance].managedObjectContext;
    _qrLocation = (QRLocation *)[NSEntityDescription insertNewObjectForEntityForName:@"QRLocation" inManagedObjectContext:context];
    _qrLocation.content = _qrData;
    if ([self parse]) {
        return _qrLocation;
    }
    // We delete it if the parsing was faulty
    [context deleteObject:_qrLocation];
    return nil;
}

- (BOOL)parse {
    _qrData = [_qrData substringFromIndex:4];
    NSArray *coordinates = [_qrData componentsSeparatedByString:@","];
    if ([coordinates count] > 1) {
        _qrLocation.latitude = [[coordinates objectAtIndex:0] doubleValue];
        _qrLocation.longitude = [[coordinates objectAtIndex:1] doubleValue];
    }
    return _qrLocation.latitude * _qrLocation.longitude != 0;
}

@end
